import 'package:flutter/material.dart';
import 'package:flutter_09_game/base/controller/base_controller.dart';
import 'package:flutter_09_game/generated/locales.g.dart';
import 'package:flutter_09_game/user/app_user_manager.dart';
import 'package:flutter_09_game/utils/loading/loading_utils.dart';
import 'package:get/get.dart';

class ProfileEditNameLogic extends BaseController {
  /// 用户名输入控制器
  final TextEditingController nameController = TextEditingController();

  /// 当前字符数
  final RxInt currentLength = 0.obs;

  /// 最大字符数
  static const int maxLength = 20;

  /// 最小字符数
  static const int minLength = 2;

  /// 是否可以保存
  final RxBool canSave = false.obs;

  RxString nameRx = ''.obs;

  @override
  void onInit() {
    super.onInit();
    nameController.text = AppUserManager().user.value?.username ?? '';
    nameRx.value = nameController.text;
  }

  @override
  void onClose() {
    nameController.dispose();
    super.onClose();
  }

  /// 保存用户名
  Future<void> saveUserName() async {
    if (!canSave.value) {
      LoadingUtils.showToast(LocaleKeys.pleaseEnterUsername.tr);
      return;

    }

    final newName = nameController.text.trim();

    // 调用API保存用户名
    final response = await AppUserManager.updateUserInfoToServer(
      username: newName,
    );

    // LoadingUtils.dismiss();

    if (response.isSuccess) {
      LoadingUtils.showToast(LocaleKeys.setSuccess.tr);
      // 返回上一页
      Get.back();
    }
  }

  /// 获取字符计数显示文本
  String get characterCountText => '$currentLength/$maxLength';
}
